package com.qyhl.webtv.module_microvideo.shortvideo.shoot.upload;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * 上传页面
 */
@Route(path = ARouterPathConstant.SHORT_VIDEO_UPLOAD)
public class ShortVideoUploadActivity extends BaseActivity implements ShortVideoUploadContract.ShortVideoUploadView {

    @BindView(R2.id.comment_btn)
    Button commentBtn;
    @BindView(R2.id.content)
    EditText content;
    @BindView(R2.id.tag_delete)
    ImageView tagDelete;
    @BindView(R2.id.tag_name)
    TextView tagName;

    @BindView(R2.id.cover)
    ImageView cover;
    @BindView(R2.id.content_num)
    TextView contentNum;

    @Autowired(name = "path")
    String videoPath;
    @Autowired(name = "cover")
    String videoCover;
    @Autowired(name = "id")
    String activityId;

    private int tagId = 0;

    private String tagTitle;

    private ShortVideoUploadPresenter mPresenter;


    /**
     * 上传token
     */
    private UpTokenBean mUpToken;

    private boolean isUploading = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.micro_activity_short_video_upload;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ShortVideoUploadPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
    }

    private void initView() {
        Glide.with(this)
                .load(videoCover)
                .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                .into(cover);
    }

    private void setListeners() {
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                contentNum.setText(s.toString().length() + "/50");
                if (StringUtils.isNotEmpty(s.toString())) {
                    commentBtn.setEnabled(true);
                } else {
                    commentBtn.setEnabled(false);
                }
            }
        });
    }

    private void checkData() {
        if (!isUploading) {
            isUploading = true;
            showSimpleLoading();
            final String upTitle = content.getText().toString();
            if (StringUtils.isEmpty(upTitle)) {
                showToast("视频描述不能为空！", 4);
                dismissLoading();
                isUploading = false;
                return;
            }

//            if (StringUtils.isEmpty(tagTitle) || tagId < 0) {
//                showToast("主题不能为空！", 4);
//                dismissLoading();
//                isUploading = false;
//                return;
//            }

            if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
                showToast("用户信息审核中，暂时无法使用该功能！", INFO);
                dismissLoading();
                isUploading =false;
                return;
            }

            if (StringUtils.isNotEmpty(videoCover) && StringUtils.isNotEmpty(videoPath)) {
                if (mUpToken == null) {
                    dismissLoading();
                    isUploading = false;
                    mPresenter.getToken(true);
                    return;
                }
                List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
                UploadBean videoBean = new UploadBean();
                videoBean.setType(3);
                videoBean.setPath(videoPath);
                videoBean.setPostion(0);
                uploadBeans.add(videoBean);

                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(4);
                videoCoverBean.setPath(videoCover);
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);

                QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getUptoken(), mUpToken.getPrefix(), new UploadResultListener() {
                    @Override
                    public void uplaodError() {
                        dismissLoading();
                        isUploading = false;
                        showToast("上传出错", 4);
                    }

                    @Override
                    public void uploadSuccess(List<UploadBean> files) {
                        if (files != null && files.size() > 0) {
                            String upCover = "";
                            String upUrl = "";
                            for (int i = 0; i < files.size(); i++) {
                                UploadBean uploadBean = files.get(i);
                                String path = uploadBean.getUrl();
                                if (uploadBean.getType() == 3) {
                                    upUrl = path;
                                } else if (uploadBean.getType() == 4) {
                                    upCover = path;
                                }
                            }
                            String userName = CommonUtils.getInstance().getUserName();
                            mPresenter.upLoadData(upTitle, upUrl, upCover, userName, tagId + "", activityId);
                        } else {
                            dismissLoading();
                            isUploading = false;
                            showToast("上传出错", 4);
                        }

                    }

                    @Override
                    public void uploadPre(double percent) {
                        setPro((int) percent);
                    }
                });
            } else {
                showToast("视频地址或封面不能为空！", 4);
                isUploading = false;
                dismissLoading();
            }
        }

    }


    @OnClick({R2.id.back_btn, R2.id.comment_btn, R2.id.cover, R2.id.tag_delete, R2.id.tag_name})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back_btn) {
            finish();
        } else if (i == R.id.comment_btn) {
            if (NetUtil.isNetworkAvalible(this)) {
                checkData();
            } else {
                showToast("网络异常，请检查您的网络！", 4);
            }
        } else if (i == R.id.cover) {
            Bundle bundle = new Bundle();
            bundle.putString(IntentKey_VideoUrl, videoPath);
            bundle.putString(IntentKey_VideoCover, videoCover);
            RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL,bundle);
        } else if (i == R.id.tag_delete) {
            tagDelete.setVisibility(View.GONE);
            tagName.setText("#点击添加主题#");
            tagName.setTextColor(getResources().getColor(R.color.micro_short_video_theme_tag_txt));
            tagName.setEnabled(true);
        } else if (i == R.id.tag_name) {
            Bundle bundle = new Bundle();
            bundle.putString("id", activityId);
            RouterManager.router(this,ARouterPathConstant.SHORT_VIDEO_TAG_SELECT,bundle,7);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                tagId = data.getIntExtra("id", -1);
                tagTitle = data.getStringExtra("title");
                if (StringUtils.isNotEmpty(tagTitle)) {
                    tagName.setText("#" + tagTitle + "#");
                    tagName.setEnabled(false);
                    tagName.setTextColor(getResources().getColor(R.color.global_black_lv1));
                    tagDelete.setVisibility(View.VISIBLE);
                    if (StringUtils.isNotEmpty(content.getText().toString())) {
                        commentBtn.setEnabled(true);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        isUploading = false;
        if (isUpload) {
            dismissLoading();
            Toasty.normal(this, "上传失败！").show();
        }
    }

    @Override
    public void upLoadSuccess(String msg) {
        dismissLoading();
        isUploading = false;
        showToast(msg, 4);
        BusFactory.getBus().post(new Event.finishActivity());
        finish();
    }

    @Override
    public void upLoadError(String msg) {
        dismissLoading();
        isUploading = false;
        showToast(msg, 4);
    }
}
